/**
 * Created by Administrator on 2017/3/21.
 */
import React, { Component, Fragment } from 'react';
import { Form, Button, Badge, Radio, Tooltip, DatePicker, Descriptions, Tag, Icon as AIcon, Switch, message } from 'antd';
import { connect } from 'dva';
import forEach from 'lodash/forEach';
import request from '@/utils/request';
import { getTimeDistance,download,formateObjToParamStr } from '@/utils/utils';
import moment from 'moment';
import ReactEcharts from 'echarts-for-react';
import ReactDataGrid from 'react-data-grid';
import find from 'lodash/find';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import { Vector } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import Feature from 'ol/Feature';
import { Icon, Style } from 'ol/style';
import Point from 'ol/geom/Point';
import { fromLonLat, toLonLat } from 'ol/proj';
import yali from './../../images/yali_blue.png';
import config from '../../config/config';

const ButtonGroup = Button.Group;

class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      detail: {},
      totalVal: 0,
      showType: 1,
      historyData: [],
      showCustom: false,
      rangePickerValue: [moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', 'YYYY-MM-DD'), moment(new Date(), 'YYYY-MM-DD')],
      layers: [
        new TileLayer({
          title: '天地图卫星影像',
          visible: false,
          source: new XYZ({
            url: 'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=49ea1deec0ffd88ef13a3f69987e9a63',
          }),
        }),
        new TileLayer({
          title: '天地图路网',
          visible: true,
          source: new XYZ({
            url: 'http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=49ea1deec0ffd88ef13a3f69987e9a63',
          }),
        }),
        new TileLayer({
          title: '天地图文字标注',
          source: new XYZ({
            url: 'http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=49ea1deec0ffd88ef13a3f69987e9a63',
          }),
        }),

      ],
    };
  }

  componentDidMount() {
    const that = this;
    that.fetchDetail();
    that.fetch();

  }

  fetchDetail = () => {
    const that = this;
    request(`/pressure_sensors/${this.props.id}`, {
      method: 'GET',
      params: {},
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          detail: response.data.data,
        }, function() {
          let pointerLayer = null;
          let map = this.map = new Map({
            target: 'press_sensor_map_view',
            layers: this.state.layers,
            view: new View({
              center: fromLonLat([that.state.detail.longitude,that.state.detail.latitude]),//经纬度
              zoom: 16,
              maxZoom: 18,
              minZoom: 5,
            }),
          });
          let mockvectorSource = that.createApoint(fromLonLat([that.state.detail.longitude,that.state.detail.latitude]));
          // 创建标注图层
          pointerLayer = new Vector({
            source: mockvectorSource,
          });
          // 将标注图层添加到地图上
          map.addLayer(pointerLayer);
        });
      }


    });
  };
  createApoint = (coordinate) => {
    let point = new Feature({
      geometry: new Point(coordinate),
      name: '压力传感器',
    });
    //设置图标的样式
    point.setStyle(new Style({
      /**{olx.style.IconOptions}类型*/
      image: new Icon({
        anchorOrigin: 'top-right',
        offsetOrigin: 'top-right',
        src: yali,
      }),
    }));

    // 创建标注的数据源
    let mockvectorSource = new VectorSource({
      features: [point],
    });
    return mockvectorSource;
  };
  onChangeShowType = e => {
    this.setState({
      showType: e.target.value,
    });
  };

  isActive(type) {
    const { rangePickerValue } = this.state;
    const value = getTimeDistance(type);
    if (!rangePickerValue[0] || !rangePickerValue[1]) {
      return false;
    }
    if (rangePickerValue[0].isSame(value[0], 'day') && rangePickerValue[1].isSame(value[1], 'day')) {
      return true;
    }
  }

  selectDate = (type) => {
    const that = this;
    this.setState({
      rangePickerValue: getTimeDistance(type),
    }, function() {
      that.fetch();
    });
  };
  fetch = (cb) => {
    const that = this;
    request(`/pressure_analysis`, {
      method: 'GET',
      params: {
        pressure_sensor_id: this.props.id,
        start_date: that.state.rangePickerValue[0].format('YYYY-MM-DD'),
        end_date: that.state.rangePickerValue[1].format('YYYY-MM-DD'),
      },
    }).then((response) => {
      console.log(response);
      if (response.status === 200) {
        this.setState({
          historyData: response.data.data,
        });
      }

    });
  };
  getOption = () => {
    const { detail } = this.state;
    const data = this.state.historyData;
    let Date = [];
    let Data = [];
    let diffData = [];
    let errDataIndex = [];
    let warmDataIndex = [];
    let difference_value = 0;
    forEach(data, (value, index) => {
      Date.push(value.upload_time);
      Data.push(value.pressure);
      if (value.pressure_status !== 0) {
        errDataIndex.push(index);
      }
      diffData.push(value.voltage);
    });

    let option = {
      background: 'rgba(0,0,0,1)',
      color: ['#1e9680', '#fe5810'],
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: ['压力', '电压'],
      },
      xAxis: [
        {
          type: 'category',
          data: Date,
          axisPointer: {
            type: 'shadow',
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          name: '压力(柱状图)',
          axisLabel: {
            formatter: '{value}(MPA)',
          },
        },
        {
          type: 'value',
          name: '电压(曲线图)',
          axisLabel: {
            formatter: '{value}(V)',
          },
          splitLine: {
            show: false,
          },
        },
      ],
      grid: {
        top: '12%',
        left: '2%',
        right: '2%',
        bottom: '4%',
        containLabel: true,
      },
      dataZoom: [
        {
          type: 'slider',
          show: false,
          xAxisIndex: [0],
        },
        {
          type: 'inside',
          xAxisIndex: [0],
        },
      ],
      series: [
        {
          name: '压力',
          type: 'bar',
          data: Data,
          itemStyle: {
            normal: {
              color: function(value) {
                if (errDataIndex.indexOf(value.dataIndex) >= 0) {
                  return '#c23531';
                } else {
                  return '#1e9680';
                }
              },
            },
          },
        },
        {
          name: '电压',
          type: 'line',
          yAxisIndex: 1,
          symbolSize: 8,
          data: diffData,
          smooth: true,
          itemStyle: {
            normal: {
              color: '#fe5810',
            },
          },
        },
      ],
    };
    return option;
  };
  handleRangePickerChange = (datePickerValue, type) => {
    const that = this;
    if (type === 'start') {
      this.setState({
        rangePickerValue: [datePickerValue, this.state.rangePickerValue[1]],
      }, function() {
        that.fetch();
      });
    } else {
      this.setState({
        rangePickerValue: [this.state.rangePickerValue[0], datePickerValue],
      }, function() {
        that.fetch();
      });
    }
  };
  renderStatus = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case 1:
        type = 'check-circle', color = '#0026ff', text = '在线';
        break;
      case -1:
        type = 'close-circle', color = '#fe1b2e', text = '离线';
        break;
      default:
        type = 'close-circle', color = '#eb2f96', text = '异常';
        break;
    }
    return <Fragment> <AIcon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };
  renderValueStatus = (val) => {
    let status = 'success';
    let explain = '';
    switch (val) {
      case 4:
        status = 'error';
        explain = '子设备失联';
        break;
      case 1:
        status = 'warning';
        explain = '电池电压低';
        break;
      case 0:
        status = 'success';
        explain = '正常';
        break;
      default:
        status = 'warning';
        explain = '未知';
    }
    return (
      <p>
        <Badge status={status}/>{explain}
      </p>
    );
  };
  renderPressStatus= (val) => {
    let status = 'success';
    let explain = '';
    switch (val) {
      case 4:
        status = 'error';
        explain = '压力传感器故障';
        break;
      case 2:
        status = 'warning';
        explain = '压力高于上限阀值';
        break;
      case 1:
        status = 'warning';
        explain = '压力低于下限阀值';
        break;
      case 0:
        status = 'success';
        explain = '压力正常';
        break;
      default:
        status = 'warning';
        explain = '未知';
    }
    return (
      <p>
        <Badge status={status}/>{explain}
      </p>
    );
  };
  renderF=(val)=>{
    let txt=''
    console.log('val',val);
    switch (Number(val)) {
      case 1:
        txt = '每天1次';
        break;
      case 2:
        txt = '每天2次';
        break;
      case 3:
        txt = '每天4次';
        break;
      case 4:
        txt = '每3小时1次';
        break;
      case 5:
        txt = '每两小时1次';
        break;
      case 6:
        txt = '每1小时1次';
        break;
      case 7:
        txt = '每半小时1次';
        break;
      default:
        txt = '';
    }
    return txt

  }
  handleExport=()=>{
    const payload= {
      pressure_sensor_id:this.props.id,
      start_date:this.state.rangePickerValue[0].format("YYYY-MM-DD"),
      end_date:this.state.rangePickerValue[1].format("YYYY-MM-DD"),
    }
    download(`${config.prefix}/pressure_data_files?Authorization=Bearer ${sessionStorage.getItem('token')}&${formateObjToParamStr(payload)}`)
  }
  render() {
    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '日期',
        width: 165,
        key: 'upload_time',
      },
      {
        name: '传感器状态',
        width: 120,
        key: 'sensor_status',
        formatter: (event) => {
          return this.renderValueStatus(event.value);
        },
      },
      {
        name: '压力状态',
        width: 180,
        key: 'pressure_status',
        formatter: (event) => {
          return this.renderPressStatus(event.value);
        },
      },
      {
        name: '压力(MPA)',
        width: 100,
        key: 'pressure',
      },
      {
        name: '电压(V)',
        width: 100,
        key: 'voltage',
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));
    const { detail } = this.state;
    const reverceData = [...this.state.historyData].reverse();
    return (
      <div>
        <Descriptions column={4} title={<div>
          <span>压力传感器基本信息</span>
        </div>} bordered>
          <Descriptions.Item label="名称" span={2}> <Tooltip
            title={detail.name}>{detail.name}</Tooltip></Descriptions.Item>
          <Descriptions.Item label="在线状态"  span={3}>{this.renderStatus(detail.online_status)}</Descriptions.Item>
          <Descriptions.Item label="IMEI" span={2}> <Tooltip
            title={detail.name}>{detail.imei}</Tooltip></Descriptions.Item>
          <Descriptions.Item label="IMSI"  span={2}>{detail.imsi}</Descriptions.Item>
          <Descriptions.Item label="安装地址" span={2}><Tooltip
            title={detail.address}>{detail.address}</Tooltip></Descriptions.Item>
          <Descriptions.Item label="创建时间" span={2}>{detail.created_at}</Descriptions.Item>
          <Descriptions.Item label="描述" span={4}>{detail.description}</Descriptions.Item>
        </Descriptions>
        <div id="press_sensor_map_view" style={{width:'100%',height:'250px'}}></div>
        <h3 className={'ant-descriptions-title'} style={{ marginTop: '18px' }}>压力传感器历史数据
          <Radio.Group onChange={this.onChangeShowType} style={{ marginLeft: '10px' }} value={this.state.showType}>
            <Radio value={1}>柱状图</Radio>
            <Radio value={2}>表格</Radio>
          </Radio.Group>
        </h3>
        <div>
          <ButtonGroup>
            <Button onClick={() => this.selectDate('month')} type={this.isActive('month') ? 'primary' : ''}>本月</Button>
            <Button onClick={() => this.selectDate('year')} type={this.isActive('year') ? 'primary' : ''}>本年</Button>
          </ButtonGroup>

          <DatePicker
            value={this.state.rangePickerValue[0]}
            allowClear={false}
            format="YYYY-MM-DD"
            style={{ width: 150 }}
            placeholder={'开始日期'}
            onChange={(e) => this.handleRangePickerChange(e, 'start')}
          />
          <DatePicker
            allowClear={false}
            value={this.state.rangePickerValue[1]}
            format="YYYY-MM-DD"
            placeholder={'结束日期'}
            style={{ width: 150 }}
            onChange={(e) => this.handleRangePickerChange(e, 'end')}
          />
        </div>
        <div style={{ height: '320px', marginTop: '10px' }}>
          {
            this.state.showType === 1 ?
              <Fragment>
                <ReactEcharts
                  option={this.getOption()}
                  style={{ height: '85%', width: '100%' }}
                  theme='my_theme'
                  //onChartReady={this.onChartReadyCallback}
                  //onEvents={EventsDict}
                />
                <p style={{marginBottom:'0'}}>注 : 绿色柱状图表示压力正常,红色柱状图表示压力异常</p>
              </Fragment> : <ReactDataGrid
                columns={columns}
                rowGetter={i => reverceData[i]}
                rowsCount={reverceData.length}
                minHeight={290}
              />
          }
          <Tooltip title={'导出前请先选择上方时间段'}>
            <Button block icon="export" type="primary"
                    style={{marginTop:'10px'}}
                    onClick={this.handleExport}
            >导出压力读数</Button>
          </Tooltip>
        </div>
        <div style={{marginTop:'30px'}}></div>
        <Descriptions  title={<div>
          <span>压力传感器配置</span>
        </div>} bordered>
          <Descriptions.Item label="测量速度(秒)">  {detail.config&&detail.config.measuring_speed} </Descriptions.Item>
          <Descriptions.Item label="上限压力值(MPA)">  {detail.config&&detail.config.upper_limit_pressure} </Descriptions.Item>
          <Descriptions.Item label="下限压力值(MPA)">  {detail.config&&detail.config.lower_limit_pressure} </Descriptions.Item>
          <Descriptions.Item label="上报波动值(MPA)">  {detail.config&&detail.config.fluctuation_pressure_value} </Descriptions.Item>
          <Descriptions.Item label="上报频率">  {detail.config&&this.renderF(detail.config.report_frequency)} </Descriptions.Item>
        </Descriptions>


      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);
